<!-- 产品发布 - 其它设置 -->
<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-width="80px"
    :disabled="props.isDetail"
  >
    <el-form-item v-if="formData!.type === 'food'" label="属性" prop="dishAttribute">
      <el-radio-group v-model="formData!.dishAttribute">
        <el-radio v-for="(item, index) in dishAttributeMap" :key="index" :value="Number(index)">
          {{ item }}
        </el-radio>
      </el-radio-group>
      <el-text class="w-full" size="small" type="info">
        请根据实际情况进行选择，按称重计价时将用于荤素单价的判断。
      </el-text>
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-radio-group v-model="formData!.status">
        <!-- <el-radio :label="-1">待审核</el-radio> -->
        <el-radio :value="0" class="radio">已下架</el-radio>
        <el-radio :value="1">已上架</el-radio>
        <!-- <el-radio :label="2">补货中</el-radio> -->
      </el-radio-group>
    </el-form-item>
    <el-form-item label="配送方式" prop="deliveryTypes" :title="formData!.type">
      <el-checkbox-group v-model="formData!.deliveryTypes" @change="onDeliveryTypesChange">
        <el-checkbox
          v-for="dict in getIntDictOptions(DICT_TYPE.TRADE_DELIVERY_TYPE)"
          :key="dict.value"
          :value="dict.value"
          :disabled="isDeliveryTypeDisabled(dict)"
        >
          {{ dict.label }}
        </el-checkbox>
      </el-checkbox-group>
      <el-text class="w-full" size="small" type="info">
        产品支持的配送方式，请根据实际情况进行选择，可多选。
      </el-text>
    </el-form-item>
    <el-form-item
      label="运费模板"
      prop="deliveryTemplateId"
      v-if="formData!.deliveryTypes?.includes(DeliveryTypeEnum.EXPRESS.type)"
    >
      <el-select placeholder="请选择运费模板" v-model="formData!.deliveryTemplateId">
        <el-option key="0" label="无" value="0" />
        <el-option
          v-for="item in deliveryTemplateList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-tooltip content="若未设置运费模板，将默认包邮！">
        <div class="flex items-center">
          <Icon icon="ep:question-filled" class="ml-5px" />
        </div>
      </el-tooltip>
      <div class="ml-[10px] w-[60px] flex items-center justify-between">
        <el-text class="cursor-pointer" type="primary" @click="getDeliveryTemplateList()"
          >刷新
        </el-text>
        <el-text
          class="cursor-pointer"
          type="primary"
          @click="deliveryTemplateAddEvent()"
          v-hasRole="['shop_admin']"
          >添加
        </el-text>
      </div>
    </el-form-item>
    <!-- <el-form-item label="推荐类型" prop="recommend">
      <el-radio-group v-model="formData!.recommend">
        <el-radio :value="0" class="radio">不推荐</el-radio>
        <el-radio :value="1">精选</el-radio>
        <el-radio :value="3">新品</el-radio>
        <el-radio :value="99" v-if="props.isDetail">付费推广</el-radio>
      </el-radio-group>
    </el-form-item> -->
    <el-form-item label="标签" prop="labels">
      <el-select
        v-model="formData!.labels"
        allow-create
        filterable
        multiple
        default-first-option
        :reserve-keyword="false"
        placeholder="输入或选择标签，如：招牌"
      >
        <el-option v-for="label in computedLabels" :key="label" :label="label" :value="label" />
      </el-select>
    </el-form-item>
    <el-form-item label="虚拟销量" prop="virtualSalesCount">
      <el-input-number
        v-model="formData!.virtualSalesCount"
        :min="0"
        :max="99999999"
        :step="1"
        controls-position="right"
        placeholder="请输入虚拟销量"
        class="!w-100px !md-w-180px"
      >
        <template #suffix>
          {{
            formData!.stepQuantity && formData!.unitName
              ? 'x' + formData!.stepQuantity + formData!.unitName
              : ''
          }}
        </template>
      </el-input-number>
    </el-form-item>
    <el-form-item label="起购数量" prop="limitMinQuantity">
      <el-input-number
        v-model="formData!.limitMinQuantity"
        :min="1"
        :max="formData!.stock || 99999999"
        :step="1"
        controls-position="right"
        placeholder="请输入起购数量"
        class="!w-100px !md-w-180px"
      >
        <template #suffix>
          {{
            formData!.stepQuantity && formData!.unitName
              ? 'x' + formData!.stepQuantity + formData!.unitName
              : ''
          }}
        </template>
      </el-input-number>
    </el-form-item>
    <el-form-item label="限购数量" prop="limitMaxQuantity">
      <el-input-number
        v-model="formData!.limitMaxQuantity"
        :min="0"
        :max="formData!.stock || 99999999"
        :step="1"
        controls-position="right"
        placeholder="请输入限购数量"
        class="!w-100px !md-w-180px"
      >
        <template #suffix>
          {{
            formData!.stepQuantity && formData!.unitName
              ? 'x' + formData!.stepQuantity + formData!.unitName
              : ''
          }}
        </template>
      </el-input-number>
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
// import {PropType} from 'vue'
// import {copyValueToTarget} from '@/utils'
import { propTypes } from '@/utils/propTypes'
import type { Spu } from '@/api/mall/product/spu'
import * as ExpressTemplateApi from '@/api/mall/trade/delivery/expressTemplate'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { DeliveryTypeEnum } from '@/utils/constants'
import { dishAttributeMap } from '@/views/mall/product/spu/enums'

defineOptions({ name: 'ProductOtherForm' })

const message = useMessage() // 消息弹窗

const props = defineProps({
  // propFormData: {
  //   type: Object as PropType<Spu>,
  //   default: () => {
  //   }
  // },
  activeName: propTypes.string.def(''),
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

const formRef = ref() // 表单Ref
const formData = defineModel<Spu>({}) // 表单数据
// 表单规则
const rules = reactive({
  dishAttribute: [required],
  status: [required],
  deliveryTypes: [required],
  isIntegral: [required],
  recommend: [required]
})

const computedLabels = computed(() => {
  const options = []
  if (formData.value!.labels && formData.value!.labels.length > 0) {
    options.push(...formData.value!.labels)
  }
  for (const tmp of ['招牌', '特价', '单点不送']) {
    if (!options.includes(tmp)) {
      options.push(tmp)
    }
  }
  return options
})

// /** 将传进来的值赋值给 formData */
// watch(
//   () => props.propFormData,
//   (data) => {
//     if (!data) {
//       return
//     }
//     copyValueToTarget(formData.value!, data)
//   },
//   {
//     deep: true,
//     immediate: true,
//   }
// )

const onDeliveryTypesChange = (e: any) => {
  //console.log(JSON.stringify(e))
  if (e && e.includes(DeliveryTypeEnum.NONE.type)) {
    formData.value!.deliveryTypes = [DeliveryTypeEnum.NONE.type]
    return
  }
  if (e && e.includes(DeliveryTypeEnum.ONSITE.type)) {
    formData.value!.deliveryTypes = [DeliveryTypeEnum.ONSITE.type]
  }
}

const isDeliveryTypeDisabled = (dict: any) => {
  if (
    ['mall'].includes(formData.value!.type || '') &&
    ![
      DeliveryTypeEnum.NONE.type,
      DeliveryTypeEnum.EXPRESS.type,
      DeliveryTypeEnum.PICK_UP.type,
      DeliveryTypeEnum.TAKE_OUT.type
    ].includes(Number(dict.value))
  ) {
    // 商城产品只能选择无需配送、快递发货、用户自提、同城配送
    return true
  }
  if (
    ['food'].includes(formData.value!.type || '') &&
    ![
      DeliveryTypeEnum.NONE.type,
      DeliveryTypeEnum.TAKE_OUT.type,
      DeliveryTypeEnum.OFFLINE.type
    ].includes(Number(dict.value))
  ) {
    // 美食只能选择无需配送（堂食）、同城配送（外卖）、现场核销
    return true
  }
  if (
    ['hotel', 'entertainment'].includes(formData.value!.type || '') &&
    Number(dict.value) != DeliveryTypeEnum.OFFLINE.type
  ) {
    // 酒店住宿、休闲娱乐只能选择现场核销
    return true
  }
  if (
    ['housekeeping'].includes(formData.value!.type || '') &&
    Number(dict.value) != DeliveryTypeEnum.ONSITE.type
  ) {
    // 家政服务只能选择上门服务
    return true
  }
  if (
    formData.value!.deliveryTypes?.includes(DeliveryTypeEnum.NONE.type) &&
    Number(dict.value) != DeliveryTypeEnum.NONE.type
  ) {
    return true
  }
  // noinspection RedundantIfStatementJS
  if (
    formData.value!.deliveryTypes?.includes(DeliveryTypeEnum.ONSITE.type) &&
    Number(dict.value) != DeliveryTypeEnum.ONSITE.type
  ) {
    return true
  }
  return false
}

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef)?.validate()
    // // 校验通过更新数据
    // Object.assign(props.propFormData, formData.value!)
  } catch (e) {
    message.error('【其它设置】还没填写完整')
    emit('update:activeName', 'other')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })

const deliveryTemplateList = ref<any>([]) // 运费模版
const getDeliveryTemplateList = async () => {
  deliveryTemplateList.value = await ExpressTemplateApi.getSimpleTemplateList()
}

const router = useRouter()
const deliveryTemplateAddEvent = () => {
  router.push({ name: 'DeliveryExpressTemplate' })
}

/** 初始化 */
onMounted(async () => {
  await getDeliveryTemplateList()
  if (['virtual', 'hotel', 'entertainment', 'housekeeping'].includes(formData.value!.type!)) {
    formData.value!.deliveryTypes = [DeliveryTypeEnum.NONE.type]
  }
})
</script>
